
package net.atremmedia.gwt.actionjava.examples.basics.samples;

import java.util.ArrayList;
import java.util.List;
import net.atremmedia.gwt.actionjava.examples.AJExample;
import net.atremmedia.gwt.actionjava.examples.frame.AJExampleOverview;
import actionjava.display.Graphics;
import actionjava.display.Shape;
import actionjava.events.tick.TickEvent;
import com.allen_sauer.gwt.log.client.Log;

public class Removal extends AJExample
{
	public static final String NAME = "Removal";
	public static final String DESCRIPTION = "Description";
	public static final String EXAMPLE_SRC = "https://code.google.com/p/gwt-actionjava/source/browse/trunk/aj-examples/aj-examples-basics/src/main/java/net/atremmedia/gwt/actionjava/examples/basics/samples/Removal.java";

	private List<Ball> balls;
	private int count = 20;

	public Removal(AJExampleOverview base)
	{
		super(NAME, DESCRIPTION, EXAMPLE_SRC, base);
	}

	@Override
	public void run()
	{
		balls = new ArrayList<Removal.Ball>();
		for(int i = 0;i < count;i++) {
			Ball ball = new Ball();
			ball.setX(Math.random() * getWidth());
			ball.setY(Math.random() * getHeight());
			ball.setVx(Math.random() * 2 - 1);
			ball.setVy(Math.random() * 2 - 1);

			addChild(ball);
			balls.add(ball);
		}
	}

	@Override
	public void onRenderTick(TickEvent event)
	{
		for(int i = balls.size() - 1;i >= 0;i--) {
			Ball ball = balls.get(i);
			ball.addX(ball.getVx());
			ball.addY(ball.getVy());
			if(ball.getX() - ball.getRadius() > getWidth() || ball.getX() + ball.getRadius() < 0 || ball.getY() - ball.getRadius() > getHeight() || ball.getY() + ball.getRadius() < 0) {
				removeChild(ball);
				balls.remove(ball);

				Log.info("Removed ball");

				if(balls.size() <= 0) {
					Log.fatal("All balls removed");

				}
			}

		}
	}
	private class Ball extends Shape
	{
		private double vx = 0;
		private double vy = 0;

		private double radius = 10;

		public Ball()
		{
			Graphics graphs = getGraphics();
			graphs.beginFill(getRandomColor());
			graphs.drawCircle(0, 0, radius);
			graphs.endFill();
		}

		public double getVx()
		{
			return vx;
		}

		public void setVx(double vx)
		{
			this.vx = vx;
		}

		public double getVy()
		{
			return vy;
		}

		public void setVy(double vy)
		{
			this.vy = vy;
		}

		public double getRadius()
		{
			return radius;
		}
	}
}
